package com.hrt.datasender.web.logmonitor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.springframework.stereotype.Service;

import com.btcode.log.ILog;
import com.hrt.datasender.mq.MqKit;
import com.hrt.datasender.mq.model.LogModel;
import com.hrt.log.LogMonitor;

@Service
public final class LogMonitorService {
    private final int maxLogSize = 300;
    
    private final int clearLogSize = 150;

    private HashMap<String, List<LogModel>> logModelMap = new HashMap<>();

    private HashMap<String, List<LogModel>> errorLogModelMap = new HashMap<>();

    private static volatile LogMonitorService instance;

    private LogMonitorService() {

    }

    public static LogMonitorService getInstance() {
        if (instance == null) {
            synchronized (LogMonitorService.class) {
                if (instance == null) {
                    instance = new LogMonitorService();
                }
            }
        }
        return instance;
    }

    public List<LogModel> getLogModelList(String monitorId) {

        List<LogModel> models = logModelMap.get(monitorId);

        if (models == null) {
            models = new ArrayList<>();
            logModelMap.put(monitorId, models);
        }

        if (models.size() > maxLogSize) {
            models.subList(0, clearLogSize).clear();
        }

        return models;
    }

    public List<LogModel> getErrorLogModelList(String monitorId) {

        List<LogModel> models = errorLogModelMap.get(monitorId);

        if (models == null) {
            models = new ArrayList<>();
            errorLogModelMap.put(monitorId, models);
        }

        if (models.size() > maxLogSize) {
            models.subList(0, clearLogSize).clear();
        }

        return models;
    }

    public LogModel getOneLogModel(String monitorId) {
        ILog log = LogMonitor.getInstance().getMonitorModel(monitorId);

        LogModel model = MqKit.getOneMsgFromMonitorLogMQ(log);

        List<LogModel> models = getLogModelList(monitorId);
        if (model != null) {
            models.add(model);
        }
        return model;
    }

    public LogModel getOneErrorLogModel(String monitorId) {
        ILog log = LogMonitor.getInstance().getMonitorModel(monitorId);

        LogModel model = MqKit.getOneMsgFromMonitorErrorLogMQ(log);

        List<LogModel> models = getErrorLogModelList(monitorId);
        models.add(model);

        return model;
    }

    public void clearMsg(String monitorId) {
        List<LogModel> models = logModelMap.get(monitorId);
        List<LogModel> errorModels = errorLogModelMap.get(monitorId);

        models.clear();
        errorModels.clear();
    }

}
